<?php

declare(strict_types=1);

namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\Output;

class action extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('app\command\action')
            ->addArgument('path', Argument::OPTIONAL, "your path")
            ->addArgument('param', Argument::OPTIONAL, "action param")
            ->setDescription('The run action from controller action!');
    }

    protected function execute(Input $input, Output $output)
    {
        $path = trim($input->getArgument('path'));
        $param = $input->getArgument('param');
        $param_array = [];
        if (is_string($param)) {
            $param = trim($param);
            $param_array = explode(',', $param);
            $param_array = is_array($param_array) ? $param_array : [ $param_array ];
        }
        $path_array = explode('/', $path);
        if (count($path_array) < 2) {
            $output->writeln('请输入正确的路径！');
            die;
        } elseif (count($path_array) == 2) {
            $action_name = array_pop($path_array);
            $controller_name = ucwords(join('\\', $path_array));
            $class_name = 'app\\controller\\' . $controller_name;
        } else {
            $action_name = array_pop($path_array);
            $controller_name = ucwords(array_pop($path_array));
            $namespace = join('\\', $path_array);
            $class_name = 'app\\controller\\' . $namespace . '\\' . $controller_name;
        }
        if (!class_exists($class_name)) {
            $output->writeln($class_name . '不是一个Class,请输入正确的路径！');
            die;
        }
        if ($param_array == null) {
            $res = invoke([ $class_name, $action_name ]);

        } else {
            $res = invoke([ $class_name, $action_name ], $param_array);

        }

        if (is_string($res)) {
            $output->writeln($res);
        } else {
            dump($res);
        }
    }
}
